package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQuerySceneOrderAttrService;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IOrderService;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.TargetAccountInfoVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.TargetAccountVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.TransferChangeCustVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.TransferInfoNewVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.TransferTargetCustVO;
import com.iwhalecloud.bss.kite.cucc.manager.inst.CuccKiteOfferInstAcct;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstAcct;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.AbstractModuleHandler;

/**
 * <Description> 用户过户业务模块组件
 *
 * @author chen.cheng110
 * @version 1.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module <br>
 */
@Service
public class LocalTransferCustModuleHandler extends AbstractModuleHandler {

    @Autowired
    ILocalQuerySceneOrderAttrService querySceneOrderAttrService;

    @Autowired
    IQuerySceneInstService querySceneInstService;

    @Autowired
    OperateInstAttrService operateInstAttrService;

    @Autowired
    private IOperateSceneCommonService operateSceneCommonService;

    @Autowired
    private ICustReceptionService custReceptionService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Override
    public List<TransferInfoNewVO> execute(AcceptContext context, SceneModule sceneModule) {
        TransferInfoNewVO transferInfoNewVO = getTransferInfoMoudle(context, Boolean.TRUE);

        SceneNewOfferSeneVO seneVO = (SceneNewOfferSeneVO) context.getSceneVo();
        seneVO.setTransferInfoNewVO(transferInfoNewVO);

        return Collections.singletonList(transferInfoNewVO);
    }

    @Override
    public List<ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {
        TransferInfoNewVO transferInfoNewVO = getTransferInfoMoudle(context, Boolean.FALSE);

        SceneNewOfferSeneVO seneVO = (SceneNewOfferSeneVO) context.getSceneVo();
        seneVO.setTransferInfoNewVO(transferInfoNewVO);

        return Collections.singletonList(transferInfoNewVO);
    }

    private TransferInfoNewVO getTransferInfoMoudle(AcceptContext context, Boolean isPreview) {
        String sceneInstId = context.getSceneVo().getSceneInstId();
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String custId = KiteWebContext.getContext().getCustId();
//        if (KiteStringUtils.isNotEmpty(kiteSceneInst.getNewCustId())) {
//            custId = kiteSceneInst.getNewCustId();
//        } else {
//            custId = KiteWebContext.getContext().getCustId();
//        }
        // 重提时且过户时 还原场景
        String taskCode = querySceneInstService.getExtParameterValue(sceneInstId, "taskCode");
        if (KiteStringUtils.equalsAny(taskCode, "OrderResubmit", "OrderSignedCheckSHZWY", "OrderResubmitZWY", "OrderResubmitXSWLW")
            && KiteStringUtils
            .equals(ServiceOfferConsts.SERVICE_OFFER_TRANSFER, context.getAcceptRequest().getServiceOfferId())) {
            String orderId = this.querySceneInstService
                .getExtParameterValue(context.getSceneVo().getSceneInstId(), "outOrderId");
            Map<String, Object> orderInfo = orderService.getOrderDetail(orderId);
            KitePosDTO kitePosDTO = JSONObject
                .toJavaObject(JSON.parseObject(JSON.toJSONString(orderInfo)), KitePosDTO.class);
            List<KitePosAttrDTO> attrs = kitePosDTO.getCustomer().getAttrs();
            String isDefaultAcct = "";
            String groupNewCustName = "";
            String groupOldCustName = "";

            if (KiteListUtils.isNotEmpty(attrs)) {
                for (KitePosAttrDTO attr : attrs) {
                    if (KiteStringUtils.equals("isDefaultAcct", attr.getCode())) {
                        isDefaultAcct = attr.getValue();
                    }
                    if (KiteStringUtils.equals("groupNewCustName", attr.getCode())) {
                        groupNewCustName = attr.getValue();
                    }
                    if (KiteStringUtils.equals("groupOldCustName", attr.getCode())) {
                        groupOldCustName = attr.getValue();
                    }
                }
            }
            // 过户对象
            TransferInfoNewVO transferInfoNewVO = new TransferInfoNewVO();
            Map<String, Object> transferInfosVo = new HashMap<String, Object>();
            if (!isPreview) {
                transferInfoNewVO.setIsEdit("F");
            }
            // 过户目标客户信息
            TransferTargetCustVO transferTargetCustVO = new TransferTargetCustVO();
            CuccCustInfoDetailDTO cuccCustInfoDetailDTO = custReceptionService.getCustomerInfoNew(custId);
            if (Objects.nonNull(cuccCustInfoDetailDTO)) {
                transferTargetCustVO.setCustId(cuccCustInfoDetailDTO.getCustId());
                transferTargetCustVO.setCustName(cuccCustInfoDetailDTO.getCustName());
                transferTargetCustVO.setOldCustId("");
                transferTargetCustVO.setCertTypeCode(cuccCustInfoDetailDTO.getCertiTypeCode());
                transferTargetCustVO.setCertCode(cuccCustInfoDetailDTO.getCertiCode());
                transferTargetCustVO.setGroupId(cuccCustInfoDetailDTO.getGroupId());
                transferTargetCustVO.setProvinceCode(cuccCustInfoDetailDTO.getProvinceCode());
                transferTargetCustVO.setEparchyCode(cuccCustInfoDetailDTO.getEparchyCode());
                transferTargetCustVO.setEparchyName(LocalAttrHelper.getRegionName(cuccCustInfoDetailDTO.getProvinceCode())
                    + "-" + LocalAttrHelper.getRegionName(cuccCustInfoDetailDTO.getEparchyCode()));
                transferInfosVo.put("transferTargetCustVO", transferTargetCustVO);
            }
            // 目标账户信息
            TargetAccountVO targetAccountVO = new TargetAccountVO();
            List<TargetAccountInfoVO> targetAccountInfoList = new ArrayList<>();

            if (KiteStringUtils.isEmpty(isDefaultAcct)) {
                isDefaultAcct = "1";
            }
            targetAccountVO.setIsDefaultAcct(isDefaultAcct);
            operateSceneCommonService
                .setCommonAttrValue(sceneInstId, "isDefaultAcct", isDefaultAcct,
                    AttrValueCache.getAttrValueNameByAttrNbrAndValue("ORD10018", isDefaultAcct));

            // 组装账户信息展示列表
            String instId = kiteSceneInst.getRootInstId();
            KiteOfferInst offerInst = querySceneInstService.getOfferInst(custId, instId);
            List<KiteOfferInstAcct> allAcctRels = querySceneInstService.listOfferInstAccts(custId, offerInst.getOfferInstId());
            if (KiteListUtils.isEmpty(allAcctRels)) {
                allAcctRels = new ArrayList<>();
            }
            if (KiteStringUtils.equals("0", isDefaultAcct) || (KiteStringUtils.equals("0", isDefaultAcct) && KiteStringUtils.equals("F", transferInfoNewVO.getIsEdit()))) {
                allAcctRels = allAcctRels.stream().filter(KiteOfferInstAcct -> ActionType.A.equals(KiteOfferInstAcct.getActionType())).collect(Collectors.toList());
            }
            for (KiteOfferInstAcct allAcctRel : allAcctRels) {
                    CuccKiteOfferInstAcct cuccAllAcctRel = (CuccKiteOfferInstAcct) allAcctRel;
                    TargetAccountInfoVO targetAccountInfoVO = new TargetAccountInfoVO();
                    targetAccountInfoVO.setCbssAccountCode(allAcctRel.getCbssAccountCode());
                    targetAccountInfoVO.setContractId(cuccAllAcctRel.getContractId());
                    targetAccountInfoVO.setPayName(cuccAllAcctRel.getAcctName());
                    targetAccountInfoVO.setPayModeCode(cuccAllAcctRel.getPayModeCode());
                    targetAccountInfoVO.setProvinceCode(cuccAllAcctRel.getProvinceCode());
                    targetAccountInfoVO.setEparchyCode(cuccAllAcctRel.getEparchyCode());
                    targetAccountInfoVO.setAcctId(cuccAllAcctRel.getAcctId());
                    targetAccountInfoVO.setAccountLocation(LocalAttrHelper.getRegionName(cuccAllAcctRel.getProvinceCode())
                        + "-" + LocalAttrHelper.getRegionName(cuccAllAcctRel.getEparchyCode()));

                    if (KiteStringUtils.isEmpty(cuccAllAcctRel.getOpenDateFormat())) {
                        targetAccountInfoVO.setOpenDateFormat("");
                    } else {
                        targetAccountInfoVO.setOpenDateFormat(cuccAllAcctRel.getOpenDateFormat());
                    }
                    if (KiteStringUtils.isEmpty(cuccAllAcctRel.getProvinceAcctId())) {
                        targetAccountInfoVO.setProvinceAccountId("");
                    } else {
                        targetAccountInfoVO.setProvinceAccountId(cuccAllAcctRel.getProvinceAcctId());
                    }
                    targetAccountInfoList.add(targetAccountInfoVO);
                }
            targetAccountVO.setTargetAccountInfoVO(targetAccountInfoList);
            transferInfosVo.put("targetAccountVO", targetAccountVO);

            // 用户名称变更
            if (KiteStringUtils.isEmpty(groupNewCustName)) {
                groupNewCustName = "";
            }
            if (KiteStringUtils.isEmpty(groupOldCustName)) {
                groupOldCustName = "";
            }
            TransferChangeCustVO transferChangeCustVO = new TransferChangeCustVO();
            transferChangeCustVO.setGroupOldCustName(groupOldCustName);
            transferChangeCustVO.setGroupNewCustName(groupNewCustName);
            transferInfosVo.put("transferChangeCustVO", transferChangeCustVO);
            operateSceneCommonService
                .setCommonAttrValue(sceneInstId, "groupNewCustName", groupNewCustName, groupNewCustName);
            operateSceneCommonService
                .setCommonAttrValue(sceneInstId, "groupOldCustName", groupOldCustName, groupOldCustName);

            transferInfoNewVO.setTransferInfosVo(transferInfosVo);

            return transferInfoNewVO;
        } else {
            // 过户对象
            TransferInfoNewVO transferInfoNewVO = new TransferInfoNewVO();
            Map<String, Object> transferInfosVo = new HashMap<String, Object>();
            if (!isPreview) {
                transferInfoNewVO.setIsEdit("F");
            }
            // 过户目标客户信息
            TransferTargetCustVO transferTargetCustVO = querySceneInstService.getExtParameterValue(sceneInstId, "addTransferCustInst");
            if (Objects.isNull(transferTargetCustVO)) {
                transferTargetCustVO = new TransferTargetCustVO();
                transferTargetCustVO.setCustId("");
                transferTargetCustVO.setCustName("");
                transferTargetCustVO.setOldCustId(custId);
                transferTargetCustVO.setCertTypeCode("");
                transferTargetCustVO.setCertCode("");
                transferTargetCustVO.setGroupId("");
                transferTargetCustVO.setProvinceCode("");
                transferTargetCustVO.setEparchyCode("");
                transferTargetCustVO.setEparchyName(LocalAttrHelper.getRegionName(transferTargetCustVO.getProvinceCode())
                    + "-" + LocalAttrHelper.getRegionName(transferTargetCustVO.getEparchyCode()));
            } else {
                transferTargetCustVO.setCustId(transferTargetCustVO.getCustId());
                transferTargetCustVO.setCustName(transferTargetCustVO.getCustName());
                transferTargetCustVO.setOldCustId(custId);
                transferTargetCustVO.setCertTypeCode(transferTargetCustVO.getCertTypeCode());
                transferTargetCustVO.setCertCode(transferTargetCustVO.getCertCode());
                transferTargetCustVO.setGroupId(transferTargetCustVO.getGroupId());
                transferTargetCustVO.setProvinceCode(transferTargetCustVO.getProvinceCode());
                transferTargetCustVO.setEparchyCode(transferTargetCustVO.getEparchyCode());
                transferTargetCustVO.setEparchyName(LocalAttrHelper.getRegionName(transferTargetCustVO.getProvinceCode())
                    + "-" + LocalAttrHelper.getRegionName(transferTargetCustVO.getEparchyCode()));
            }
            transferInfosVo.put("transferTargetCustVO", transferTargetCustVO);

            // 目标账户信息
            TargetAccountVO targetAccountVO = new TargetAccountVO();
            List<TargetAccountInfoVO> targetAccountInfoList = new ArrayList<>();

            String isDefaultAcct = querySceneInstService.getCommonAttrValue(sceneInstId, "isDefaultAcct");
            if (KiteStringUtils.isEmpty(isDefaultAcct)) {
                isDefaultAcct = "1";
            }
            targetAccountVO.setIsDefaultAcct(isDefaultAcct);
            operateSceneCommonService
                .setCommonAttrValue(sceneInstId, "isDefaultAcct", isDefaultAcct,
                    AttrValueCache.getAttrValueNameByAttrNbrAndValue("ORD10018", isDefaultAcct));

            // 组装账户信息展示列表
            List<KiteOfferInst> mainOfferInsts = querySceneInstService.listGiftOfferInsts(sceneInstId);
            if (KiteListUtils.isEmpty(mainOfferInsts)) {
                mainOfferInsts = querySceneInstService.listMainOfferInsts(sceneInstId);
            }
            for (KiteOfferInst offerInst : mainOfferInsts) {
                List<KiteOfferInstAcct> allAcctRels = querySceneInstService.listOfferInstAccts(custId, offerInst.getOfferInstId());
                if (KiteListUtils.isEmpty(allAcctRels)) {
                    allAcctRels = new ArrayList<>();
                }
                // 初始化时只获取当前客户的默认账户展示 过户默认账户选择"是"，预览时也需要筛选
                if (KiteStringUtils.isEmpty(kiteSceneInst.getNewCustId()) || (KiteStringUtils.equals("F",transferInfoNewVO.getIsEdit()) && KiteStringUtils.equals("1",isDefaultAcct))) {
                    allAcctRels = allAcctRels.stream().filter(KiteOfferInstAcct -> "1".equals(KiteOfferInstAcct.getIsDefault())).collect(Collectors.toList());
                    //allAcctRels = new ArrayList<>();
                }
                for (KiteOfferInstAcct allAcctRel : allAcctRels) {
                    CuccKiteOfferInstAcct cuccAllAcctRel = (CuccKiteOfferInstAcct) allAcctRel;
                    TargetAccountInfoVO targetAccountInfoVO = new TargetAccountInfoVO();
                    targetAccountInfoVO.setCbssAccountCode(allAcctRel.getCbssAccountCode());
                    targetAccountInfoVO.setContractId(cuccAllAcctRel.getContractId());
                    targetAccountInfoVO.setPayName(cuccAllAcctRel.getAcctName());
                    targetAccountInfoVO.setPayModeCode(cuccAllAcctRel.getPayModeCode());
                    targetAccountInfoVO.setProvinceCode(cuccAllAcctRel.getProvinceCode());
                    targetAccountInfoVO.setEparchyCode(cuccAllAcctRel.getEparchyCode());
                    targetAccountInfoVO.setAcctId(cuccAllAcctRel.getAcctId());
                    targetAccountInfoVO.setAccountLocation(LocalAttrHelper.getRegionName(cuccAllAcctRel.getProvinceCode())
                        + "-" + LocalAttrHelper.getRegionName(cuccAllAcctRel.getEparchyCode()));

                    if (KiteStringUtils.isEmpty(cuccAllAcctRel.getOpenDateFormat())) {
                        targetAccountInfoVO.setOpenDateFormat("");
                    } else {
                        targetAccountInfoVO.setOpenDateFormat(cuccAllAcctRel.getOpenDateFormat());
                    }
                    if (KiteStringUtils.isEmpty(cuccAllAcctRel.getProvinceAcctId())) {
                        targetAccountInfoVO.setProvinceAccountId("");
                    } else {
                        targetAccountInfoVO.setProvinceAccountId(cuccAllAcctRel.getProvinceAcctId());
                    }
                    targetAccountInfoList.add(targetAccountInfoVO);
                }
            }
            targetAccountVO.setTargetAccountInfoVO(targetAccountInfoList);
            transferInfosVo.put("targetAccountVO", targetAccountVO);

            // 用户名称变更
            String groupNewCustName = querySceneInstService.getCommonAttrValue(sceneInstId, "groupNewCustName");
            if (KiteStringUtils.isEmpty(groupNewCustName)) {
                groupNewCustName = "";
            }
            TransferChangeCustVO transferChangeCustVO = new TransferChangeCustVO();
            String oldUserName = querySceneInstService.getCommonAttrValue(sceneInstId, "group_user_name");
            if (KiteStringUtils.isEmpty(oldUserName)) {
                oldUserName = "";
            }
            transferChangeCustVO.setGroupOldCustName(oldUserName);
            transferChangeCustVO.setGroupNewCustName(groupNewCustName);
            transferInfosVo.put("transferChangeCustVO", transferChangeCustVO);
            operateSceneCommonService
                .setCommonAttrValue(sceneInstId, "groupNewCustName", groupNewCustName, groupNewCustName);
            operateSceneCommonService
                .setCommonAttrValue(sceneInstId, "groupOldCustName", oldUserName, oldUserName);

            // 保存老用户归属地
            String oldUserLocation = querySceneInstService.getCommonAttrValue(sceneInstId, "user_location");
            operateSceneInstService.putExtParameter(sceneInstId, "oldUserLocation", oldUserLocation);

            transferInfoNewVO.setTransferInfosVo(transferInfosVo);

            return transferInfoNewVO;
        }
    }
}
